package com.sh.粘包半粘包.three;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.ByteBuffer;

public class TcpServer {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(8888);
        System.out.println("服务器启动，等待客户端连接...");
        Socket socket = serverSocket.accept();
        System.out.println("客户端已连接");

        InputStream inputStream = socket.getInputStream();
        OutputStream outputStream = socket.getOutputStream();

        byte[] lengthBuffer = new byte[4];
        int bytesRead;
        while ((bytesRead = inputStream.read(lengthBuffer))!= -1) {
            if (bytesRead < 4) {
                continue;
            }
            int messageLength = ByteBuffer.wrap(lengthBuffer).getInt();
            byte[] messageBuffer = new byte[messageLength];
            int totalRead = 0;
            while (totalRead < messageLength) {
                int read = inputStream.read(messageBuffer, totalRead, messageLength - totalRead);
                if (read == -1) {
                    break;
                }
                totalRead += read;
            }
            if (totalRead == messageLength) {
                String message = new String(messageBuffer);
                System.out.println("接收到的消息：" + message);

                // 发送响应
                String response = "收到消息：" + message;
                byte[] responseBytes = response.getBytes();
                byte[] responseLengthBuffer = ByteBuffer.allocate(4).putInt(responseBytes.length).array();
                outputStream.write(responseLengthBuffer);
                outputStream.write(responseBytes);
            }
        }

        socket.close();
        serverSocket.close();
    }
}